import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/responsive_layout.dart';
import '../theme/app_theme.dart';

/**
 * 现代化输入框组件
 * 支持多种样式和交互状态
 */
class ModernInput extends StatefulWidget {
  final String? label;
  final String? hint;
  final String? helperText;
  final String? errorText;
  final IconData? prefixIcon;
  final IconData? suffixIcon;
  final VoidCallback? onSuffixIconPressed;
  final TextEditingController? controller;
  final ValueChanged<String>? onChanged;
  final VoidCallback? onTap;
  final bool obscureText;
  final bool enabled;
  final bool readOnly;
  final int? maxLines;
  final int? maxLength;
  final TextInputType? keyboardType;
  final List<TextInputFormatter>? inputFormatters;
  final FocusNode? focusNode;
  final ModernInputStyle style;
  final EdgeInsetsGeometry? contentPadding;

  const ModernInput({
    super.key,
    this.label,
    this.hint,
    this.helperText,
    this.errorText,
    this.prefixIcon,
    this.suffixIcon,
    this.onSuffixIconPressed,
    this.controller,
    this.onChanged,
    this.onTap,
    this.obscureText = false,
    this.enabled = true,
    this.readOnly = false,
    this.maxLines = 1,
    this.maxLength,
    this.keyboardType,
    this.inputFormatters,
    this.focusNode,
    this.style = ModernInputStyle.outlined,
    this.contentPadding,
  });

  @override
  State<ModernInput> createState() => _ModernInputState();
}

class _ModernInputState extends State<ModernInput>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _focusAnimation;
  late FocusNode _focusNode;
  bool _isFocused = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _focusAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    _focusNode = widget.focusNode ?? FocusNode();
    _focusNode.addListener(_onFocusChange);
  }

  @override
  void dispose() {
    _animationController.dispose();
    if (widget.focusNode == null) {
      _focusNode.dispose();
    }
    super.dispose();
  }

  /**
   * 焦点变化处理
   */
  void _onFocusChange() {
    setState(() {
      _isFocused = _focusNode.hasFocus;
    });

    if (_isFocused) {
      _animationController.forward();
    } else {
      _animationController.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        // 标签
        if (widget.label != null) ...[
          Text(
            widget.label!,
            style: theme.textTheme.labelMedium?.copyWith(
              color: widget.errorText != null
                  ? colorScheme.error
                  : colorScheme.onSurface,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: isDesktop ? 8 : 6),
        ],

        // 输入框
        AnimatedBuilder(
          animation: _focusAnimation,
          builder: (context, child) {
            return _buildInputField(context, theme, colorScheme, isDesktop);
          },
        ),

        // 帮助文本或错误文本
        if (widget.helperText != null || widget.errorText != null) ...[
          SizedBox(height: isDesktop ? 6 : 4),
          AnimatedSwitcher(
            duration: const Duration(milliseconds: 200),
            child: Text(
              widget.errorText ?? widget.helperText ?? '',
              key: ValueKey(widget.errorText ?? widget.helperText),
              style: theme.textTheme.bodySmall?.copyWith(
                color: widget.errorText != null
                    ? colorScheme.error
                    : colorScheme.onSurfaceVariant,
              ),
            ),
          ),
        ],
      ],
    );
  }

  /**
   * 构建输入框
   */
  Widget _buildInputField(
    BuildContext context,
    ThemeData theme,
    ColorScheme colorScheme,
    bool isDesktop,
  ) {
    final hasError = widget.errorText != null;
    final borderColor = hasError
        ? colorScheme.error
        : _isFocused
            ? colorScheme.primary
            : colorScheme.outline;

    final backgroundColor = widget.style == ModernInputStyle.filled
        ? colorScheme.surfaceContainerHighest.withOpacity(0.5)
        : Colors.transparent;

    return Container(
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(widget.style == ModernInputStyle.rounded ? 24 : 12),
        border: widget.style != ModernInputStyle.underlined
            ? Border.all(
                color: borderColor.withOpacity(0.7 + (_focusAnimation.value * 0.3)),
                width: 1 + (_focusAnimation.value * 0.5),
              )
            : null,
      ),
      child: TextField(
        controller: widget.controller,
        focusNode: _focusNode,
        onChanged: widget.onChanged,
        onTap: widget.onTap,
        obscureText: widget.obscureText,
        enabled: widget.enabled,
        readOnly: widget.readOnly,
        maxLines: widget.maxLines,
        maxLength: widget.maxLength,
        keyboardType: widget.keyboardType,
        inputFormatters: widget.inputFormatters,
        style: theme.textTheme.bodyLarge?.copyWith(
          fontSize: isDesktop ? 14 : 16,
        ),
        decoration: InputDecoration(
          hintText: widget.hint,
          hintStyle: theme.textTheme.bodyLarge?.copyWith(
            color: colorScheme.onSurfaceVariant,
            fontSize: isDesktop ? 14 : 16,
          ),
          prefixIcon: widget.prefixIcon != null
              ? Icon(
                  widget.prefixIcon,
                  color: _isFocused ? colorScheme.primary : colorScheme.onSurfaceVariant,
                  size: isDesktop ? 20 : 24,
                )
              : null,
          suffixIcon: widget.suffixIcon != null
              ? IconButton(
                  icon: Icon(
                    widget.suffixIcon,
                    color: _isFocused ? colorScheme.primary : colorScheme.onSurfaceVariant,
                    size: isDesktop ? 20 : 24,
                  ),
                  onPressed: widget.onSuffixIconPressed,
                )
              : null,
          contentPadding: widget.contentPadding ??
              EdgeInsets.symmetric(
                horizontal: isDesktop ? 16 : 20,
                vertical: isDesktop ? 12 : 16,
              ),
          border: widget.style == ModernInputStyle.underlined
              ? UnderlineInputBorder(
                  borderSide: BorderSide(color: borderColor),
                )
              : InputBorder.none,
          enabledBorder: widget.style == ModernInputStyle.underlined
              ? UnderlineInputBorder(
                  borderSide: BorderSide(color: colorScheme.outline),
                )
              : InputBorder.none,
          focusedBorder: widget.style == ModernInputStyle.underlined
              ? UnderlineInputBorder(
                  borderSide: BorderSide(color: colorScheme.primary, width: 2),
                )
              : InputBorder.none,
          errorBorder: widget.style == ModernInputStyle.underlined
              ? UnderlineInputBorder(
                  borderSide: BorderSide(color: colorScheme.error),
                )
              : InputBorder.none,
        ),
      ),
    );
  }
}

/**
 * 现代化搜索框组件
 */
class ModernSearchInput extends StatefulWidget {
  final String? hint;
  final TextEditingController? controller;
  final ValueChanged<String>? onChanged;
  final VoidCallback? onClear;
  final bool autofocus;
  final EdgeInsetsGeometry? margin;

  const ModernSearchInput({
    super.key,
    this.hint,
    this.controller,
    this.onChanged,
    this.onClear,
    this.autofocus = false,
    this.margin,
  });

  @override
  State<ModernSearchInput> createState() => _ModernSearchInputState();
}

class _ModernSearchInputState extends State<ModernSearchInput> {
  late TextEditingController _controller;
  bool _hasText = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? TextEditingController();
    _controller.addListener(_onTextChanged);
    _hasText = _controller.text.isNotEmpty;
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _controller.dispose();
    }
    super.dispose();
  }

  /**
   * 文本变化处理
   */
  void _onTextChanged() {
    final hasText = _controller.text.isNotEmpty;
    if (_hasText != hasText) {
      setState(() {
        _hasText = hasText;
      });
    }
    widget.onChanged?.call(_controller.text);
  }

  /**
   * 清空搜索
   */
  void _onClear() {
    _controller.clear();
    widget.onClear?.call();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    return Container(
      margin: widget.margin,
      child: ModernInput(
        controller: _controller,
        hint: widget.hint ?? '搜索...',
        prefixIcon: Icons.search_rounded,
        suffixIcon: _hasText ? Icons.clear_rounded : null,
        onSuffixIconPressed: _hasText ? _onClear : null,
        style: ModernInputStyle.filled,
        contentPadding: EdgeInsets.symmetric(
          horizontal: isDesktop ? 16 : 20,
          vertical: isDesktop ? 10 : 12,
        ),
      ),
    );
  }
}

/**
 * 输入框样式枚举
 */
enum ModernInputStyle {
  outlined,   // 边框样式
  filled,     // 填充样式
  underlined, // 下划线样式
  rounded,    // 圆角样式
}